package start

import (
	"LinkWareHouse/fzf"
	"LinkWareHouse/sqlite"
	"LinkWareHouse/storage"
	"LinkWareHouse/watch"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func addExit(p []string) []string {
	p = append(p, "Exit")
	sep := strings.Split(p[fzf.Fzf(p)], " ")
	return sep
}

func deleteAfterViewing(s *sqlite.Storage, name, link string, del bool) {
	if del {
		s.Remove(&storage.Page{Name: name, Link: link})
	}
}

func saveLink(s *sqlite.Storage) {
	var Name, Link, DelAfterViewing string
	fmt.Print("Enter link:\n> ")
	fmt.Scan(&Link)
	fmt.Print("Enter name:\n> ")
	fmt.Scan(&Name)

	fmt.Print("You want delete this link after watching (false/true or f/t or 0/1)\n> ")
	fmt.Scan(&DelAfterViewing)
	boolValue, _ := strconv.ParseBool(DelAfterViewing)

	s.Save(&storage.Page{Name: Name, Link: Link, DelAfterViewing: boolValue})
}

func selectLink(s *sqlite.Storage) error {
	sep := addExit(s.GetRow())
	if sep[0] != "Exit" {
		boolValue, _ := strconv.ParseBool(sep[2])
		deleteAfterViewing(s, sep[0], sep[1], boolValue)
		watch.OpenBrowser(sep[1])
	}
	return nil
}

func pickRandom(s *sqlite.Storage) error {
	p, err := s.PickRandom()
	if err == nil {
		deleteAfterViewing(s, p.Name, p.Link, p.DelAfterViewing)
		fmt.Printf("%s %s\n", p.Name, p.Link)
		watch.OpenBrowser(p.Link)
	}

	return nil
}

func removeLink(s *sqlite.Storage) error {
	sep := addExit(s.GetRow())
	if sep[0] != "Exit" {
		return s.Remove(&storage.Page{Name: sep[0], Link: sep[1]})
	}
	return nil
}

func Start(s *sqlite.Storage) {
	choice := []string{"Add new", "Select", "Pick random", "Remove", "Exit"}
	for {
		switch fzf.Fzf(choice) {
		case 0:
			saveLink(s)
		case 1:
			selectLink(s)
		case 2:
			pickRandom(s)
		case 3:
			removeLink(s)
		case 4:
			os.Exit(0)
		}
	}
}
